#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setGeometry(0, 0, 800, 480);
    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);

    pushButton[0] = new QPushButton();
    pushButton[0]->setText("开始监听");
    pushButton[1] = new QPushButton();
    pushButton[1]->setText("停止监听");
    pushButton[1]->setEnabled(false);
    pushButton[2] = new QPushButton();
    pushButton[2]->setText("清空文本");
    pushButton[3] = new QPushButton();
    pushButton[3]->setText("发送消息");

    label[0] = new QLabel();
    label[0]->setText("监听IP:");
    label[0]->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    label[1] = new QLabel();
    label[1]->setText("监听PORT:");
    label[1]->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    textBrowser = new QTextBrowser();

    comboBox = new QComboBox();/* 显示本地IP */
    spinBox = new QSpinBox();/* 选择端口号 */
    spinBox->setRange(10000, 99999);

    lineEdit = new QLineEdit();/* 文本输入框 */
    lineEdit->setText("请输入要发送的内容");

    hWidget[0] = new QWidget();
    hBoxLayout[0] = new QHBoxLayout();
    hBoxLayout[0]->addWidget(label[0]);
    hBoxLayout[0]->addWidget(comboBox);
    hBoxLayout[0]->addWidget(label[1]);
    hBoxLayout[0]->addWidget(spinBox);
    hWidget[0]->setLayout(hBoxLayout[0]);

    hWidget[1] = new QWidget();
    hBoxLayout[1] = new QHBoxLayout();
    hBoxLayout[1]->addWidget(pushButton[0]);
    hBoxLayout[1]->addWidget(pushButton[1]);
    hBoxLayout[1]->addWidget(pushButton[2]);
    hWidget[1]->setLayout(hBoxLayout[1]);

    hWidget[2] = new QWidget();
    hBoxLayout[2] = new QHBoxLayout();
    hBoxLayout[2]->addWidget(lineEdit);
    hBoxLayout[2]->addWidget(pushButton[3]);
    hWidget[2]->setLayout(hBoxLayout[2]);

    vWidget = new QWidget();
    vBoxLayout = new QVBoxLayout();
    vBoxLayout->addWidget(textBrowser);
    vBoxLayout->addWidget(hWidget[0]);
    vBoxLayout->addWidget(hWidget[1]);
    vBoxLayout->addWidget(hWidget[2]);
    vWidget->setLayout(vBoxLayout);

    setCentralWidget(vWidget);

    getLocalHostIp();

    connect(pushButton[0], &QPushButton::clicked, this, &MainWindow::startListen);
    connect(pushButton[1], &QPushButton::clicked, this, &MainWindow::stopListen);
    connect(pushButton[2], &QPushButton::clicked, this, &MainWindow::clearTestBrowser);
    connect(pushButton[3], &QPushButton::clicked, this, &MainWindow::sendMessages);
    connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::clientConnect);
}

MainWindow::~MainWindow()
{

}

void MainWindow::getLocalHostIp()
{
#if 0
    /* 获取主机名称 */
    QString hostName = QHostInfo::localHostName();
    QHostInfo hostInfo = QHostInfo::fromName(hostName);
    IPList = hostInfo.addresses();
    qDebug() << IPList << endl;
    foreach (auto &ip, IPList) {
        if (ip.protocol() == QAbstractSocket::IPv4Protocol) {
            comboBox->addItem(ip.toString());
        }
    }
#else
    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
    foreach (auto &interface, list) {
        QList<QNetworkAddressEntry> entryList = interface.addressEntries();
        foreach (auto& entry, entryList) {
            if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                comboBox->addItem(entry.ip().toString());
                IPList << entry.ip();
            }
        }
    }
#endif
}

void MainWindow::clientConnect()
{
    tcpSocket = tcpServer->nextPendingConnection();/* 获取客户端套接字 */
    QString ip = tcpSocket->peerAddress().toString();
    quint16 port = tcpSocket->peerPort();
    textBrowser->append("客户端已连接");
    textBrowser->append("ip:" + ip + "port:" + QString::number(port));
    connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::recvMessages);
    connect(tcpSocket, &QTcpSocket::stateChanged, this, &MainWindow::socketStateChange);
}

void MainWindow::startListen()
{
    if (comboBox->currentIndex() == -1) {
        return;
    }

    qDebug() << "start listen..." << endl;

    tcpServer->listen(IPList[comboBox->currentIndex()], spinBox->value());
    pushButton[0]->setEnabled(false);
    pushButton[1]->setEnabled(true);
    comboBox->setEnabled(false);
    spinBox->setEnabled(false);

    textBrowser->append("服务端IP:" + comboBox->currentText());
    textBrowser->append("监听端口:" + spinBox->text());
}

void MainWindow::stopListen()
{
    tcpServer->close();

    if (tcpSocket->state() == tcpSocket->ConnectedState) {
        tcpSocket->disconnectFromHost();
    }

    pushButton[0]->setEnabled(true);
    pushButton[1]->setEnabled(false);
    comboBox->setEnabled(true);
    spinBox->setEnabled(true);

    textBrowser->append("已停止监听端口:" + spinBox->text());
}

void MainWindow::clearTestBrowser()
{
    textBrowser->clear();
}

void MainWindow::recvMessages()
{
    textBrowser->append("客户端：" + tcpSocket->readAll());
}

void MainWindow::sendMessages()
{
    if (tcpSocket == nullptr) {
        return;
    }
    if (tcpSocket->state() != tcpSocket->ConnectedState) {
        return;
    }
    tcpSocket->write(lineEdit->text().toUtf8().data());
    textBrowser->append("服务端:" + lineEdit->text());
}

void MainWindow::socketStateChange(QAbstractSocket::SocketState state)
{
    qDebug() << state << endl;
}
